﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using PMPUtils.Form;
using PMPUtils.DB;
using PMPUtils.Management;
using PMPUtils.Resources;

namespace PMP.Management
{
    public partial class MOM : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FormUtil.AuthenticateLead(Session, Response);

                try
                {
                    RefreshTreeView();
                    RefreshGridViews(null);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }
        }

        protected void trvMOMs_SelectedNodeChanged(object sender, EventArgs e)
        {
            try
            {
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
            }
        }

        private void RefreshTreeView()
        {
            int rootIndex = -1;
            int parentIndex = -1;
            int nodeIndex = -1;
            TreeNode selectedNode = trvMOMs.SelectedNode;

            if (selectedNode == null)
            {
                pnlCategory.Visible = false;
                pnlMoM.Visible = false;
                pnlDetails.Visible = false;

                btnAddCategory.Visible = false;
                btnAddMOM.Visible = false;

                rootIndex = 0;

                RefreshGridViews(null);
            }

            // If select the root
            if (selectedNode == null || selectedNode.Parent == null)
            {
                pnlCategory.Visible = true;
                pnlMoM.Visible = false;
                pnlDetails.Visible = false;

                btnAddCategory.Visible = true;
                btnAddMOM.Visible = false;

                rootIndex = 0;

                RefreshGridViews(null);
            }
            // Select the category node
            else if (selectedNode.Parent != null && selectedNode.Parent.Parent == null)
            {
                pnlCategory.Visible = false;
                pnlMoM.Visible = true;
                pnlDetails.Visible = false;

                btnAddCategory.Visible = false;
                btnAddMOM.Visible = true;

                rootIndex = trvMOMs.Nodes.IndexOf(selectedNode.Parent);
                parentIndex = selectedNode.Parent.ChildNodes.IndexOf(selectedNode);

                RefreshGridViews(null);
            }
            // Select the mom node
            else
            {
                pnlCategory.Visible = false;
                pnlMoM.Visible = false;
                pnlDetails.Visible = true;

                btnAddCategory.Visible = false;
                btnAddMOM.Visible = false;

                // Refresh Agenda
                String momID = selectedNode.Value;

                RefreshGridViews(momID);

                rootIndex = trvMOMs.Nodes.IndexOf(selectedNode.Parent.Parent);
                parentIndex = selectedNode.Parent.Parent.ChildNodes.IndexOf(selectedNode.Parent);
                nodeIndex = selectedNode.Parent.ChildNodes.IndexOf(selectedNode);

                MOMOperator.RefreshTreeView(trvMOMs);

                trvMOMs.ExpandAll();
                trvMOMs.Nodes[rootIndex].ChildNodes[parentIndex].ChildNodes[nodeIndex].Select();

                return;
            }

            MOMOperator.RefreshTreeView(trvMOMs);
            RefreshGridViews(null);

            if (rootIndex != -1 && parentIndex != -1 && nodeIndex != -1)
            {
                trvMOMs.ExpandAll();
                trvMOMs.Nodes[rootIndex].ChildNodes[parentIndex].ChildNodes[nodeIndex].Select();
            }
            else if (rootIndex != -1 && parentIndex != -1)
            {
                trvMOMs.ExpandAll();
                trvMOMs.Nodes[rootIndex].ChildNodes[parentIndex].Select();
            }
            else
            {
                trvMOMs.ExpandAll();
                trvMOMs.Nodes[0].Select();
            }
        }

        protected void btnAddCategory_Click(object sender, EventArgs e)
        {
            String description = txtCategoryDesc.Text.Trim();

            if (description.Equals(String.Empty))
            {

                Messenger.Show(Response, "Need to specify the description for the category!");
                return;
            }

            try
            {
                String strInsertCategory = "insert into mom_type (coldsc) values ('" + description + "')";
                DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                localOperator.Update(strInsertCategory);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            MOMOperator.RefreshTreeView(trvMOMs);

            foreach (TreeNode categoryNode in trvMOMs.Nodes[0].ChildNodes)
            {
                if (categoryNode.Text.Trim().Equals(description.Trim()))
                {
                    categoryNode.Select();
                    trvMOMs.ExpandAll();

                    RefreshGridViews(null);
                    break;
                }
            }
        }

        private void RefreshGridViews(String momID)
        {
            if (momID == null)
            {
                RefreshMOM(String.Empty);
                RefreshAgenda(String.Empty);
                RefreshDecision(String.Empty);
                RefreshActions(String.Empty);
                RefreshNotes(String.Empty);
            }
            else
            {
                RefreshMOM(momID);
                RefreshAgenda(momID);
                RefreshDecision(momID);
                RefreshActions(momID);
                RefreshNotes(momID);
            }
        }

        protected void grvMOM_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvMOM.EditIndex = (int)e.NewEditIndex;
            
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvAgenda.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvDecision.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvNotes.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvActions.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void grvMOM_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void grvMOM_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void grvMOM_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void btnAddMOM_Click(object sender, EventArgs e)
        {
            TreeNode categoryNode = trvMOMs.SelectedNode;
            String category = categoryNode.Value;

            String title = txtTitle.Text.Trim();
            String chairman = txtChairman.Text.Trim();
            String duration = txtDuration.Text.Trim();
            String attendee = txtAttendee.Text.Trim();
            String copyto = txtCopyTo.Text.Trim();
            String meeting_date = txtDate.Text.Trim();
            String created_date = txtMOMDate.Text.Trim();
            String created_by = txtCreatedBy.Text.Trim();
            String next = txtNextDate.Text.Trim();

            if (title.Equals(String.Empty) ||
               chairman.Equals(String.Empty) ||
               duration.Equals(String.Empty) ||
               attendee.Equals(String.Empty) ||
               copyto.Equals(String.Empty) ||
               meeting_date.Equals(String.Empty) ||
               created_date.Equals(String.Empty) ||
               created_by.Equals(String.Empty) ||
               next.Equals(String.Empty))
            {
                Messenger.Show(Response, "Please fill all required fields!");
                return;
            }

            try
            {
                String strInsertMOM = "insert into mom (category, title, chairman, duration, attendee, copyto, meeting_date, created_date, created_by, next) values " +
                    "(" + category + ", '" + title + "', '" + chairman + "', " + duration + ", '" + attendee + "', '" + copyto + "', '" + meeting_date + "', '" + created_date + "', '" + created_by + "', '" + next + "')";
                DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                localOperator.Update(strInsertMOM);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            String newMOMTitle = txtTitle.Text.Trim();

            // Clean up the fields
            txtTitle.Text = String.Empty;
            txtChairman.Text = String.Empty;
            txtDuration.Text = String.Empty;
            txtAttendee.Text = String.Empty;
            txtCopyTo.Text = String.Empty;
            txtDate.Text = String.Empty;
            txtMOMDate.Text = String.Empty;
            txtCreatedBy.Text = String.Empty;
            txtNextDate.Text = String.Empty;

            MOMOperator.RefreshTreeView(trvMOMs);

            foreach (TreeNode categoryNodeToVerify in trvMOMs.Nodes[0].ChildNodes)
            {
                if (categoryNodeToVerify.Value.Trim().Equals(category.Trim()))
                {
                    foreach (TreeNode momNodeToVerify in categoryNodeToVerify.ChildNodes)
                    {
                        if (momNodeToVerify.Text.Trim().Equals(newMOMTitle))
                        {
                            momNodeToVerify.Select();
                            trvMOMs.ExpandAll();

                            String momID = momNodeToVerify.Value.Trim();
                            RefreshGridViews(momID);

                            break;
                        }
                    }
                }
            }
        }

        protected void btnAddAgenda_Click(object sender, EventArgs e)
        {
            TreeNode momNode = trvMOMs.SelectedNode;
            String momID = momNode.Value;

            String agenda = txtAgenda.Text.Trim();
            agenda = agenda.Replace("\'", "\"");
            String duration = txtAgendaDuration.Text.Trim();
            String presenter = txtPresenter.Text.Trim();

            if (agenda.Equals(String.Empty) ||
               presenter.Equals(String.Empty) ||
               duration.Equals(String.Empty))
            {
                Messenger.Show(Response, "Please fill all required fields!");
                return;
            }

            try
            {
                String strInsertAgenda = "insert into mom_agenda (mom_id, agenda, duration, presenter) values " +
                    "(" + momID + ", '" + agenda + "', " + duration + ", '" + presenter + "')";
                DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                localOperator.Update(strInsertAgenda);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            // Clean up the fields
            txtAgenda.Text = String.Empty;
            txtAgendaDuration.Text = String.Empty;
            txtPresenter.Text = String.Empty;

            RefreshGridViews(momID);
        }

        protected void btnAddDecision_Click(object sender, EventArgs e)
        {
            TreeNode momNode = trvMOMs.SelectedNode;
            String momID = momNode.Value;

            String decision = txtDecision.Text.Trim();
            decision = decision.Replace("\'", "\"");
            String duedate = txtDecDueDate.Text.Trim();
            String decisionMaker = txtMaker.Text.Trim();

            if (decision.Equals(String.Empty) ||
               duedate.Equals(String.Empty) ||
               decisionMaker.Equals(String.Empty))
            {
                Messenger.Show(Response, "Please fill all required fields!");
                return;
            }

            try
            {
                String strInsertDecision = "insert into mom_decision (mom_id, decision, duedate, maker) values " +
                    "(" + momID + ", '" + decision + "', '" + duedate + "', '" + decisionMaker + "')";
                DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                localOperator.Update(strInsertDecision);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            // Clean up the fields
            txtDecision.Text = String.Empty;
            txtDecDueDate.Text = String.Empty;
            txtMaker.Text = String.Empty;

            RefreshGridViews(momID);
        }

        protected void btnAddNote_Click(object sender, EventArgs e)
        {
            TreeNode momNode = trvMOMs.SelectedNode;
            String momID = momNode.Value;

            String note = txtNote.Text.Trim();
            note = note.Replace("\'", "\"");

            if (note.Equals(String.Empty))
            {
                Messenger.Show(Response, "Please fill all required fields!");
                return;
            }

            try
            {
                String strInsertNote = "insert into mom_notes (mom_id, notes) values " +
                    "(" + momID + ", '" + note + "')";
                DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                localOperator.Update(strInsertNote);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            // Clean up the fields
            txtNote.Text = String.Empty;

            RefreshGridViews(momID);
        }

        protected void btnAddAction_Click(object sender, EventArgs e)
        {
            TreeNode momNode = trvMOMs.SelectedNode;
            String momID = momNode.Value;

            String action = txtAction.Text.Trim();
            action = action.Replace("\'", "\"");
            String status = txtActionSts.Text.Trim();
            String dueDate = txtActionDueDate.Text.Trim();
            String owner = ddlOwners.SelectedValue.Trim();

            if (action.Equals(String.Empty) ||
               status.Equals(String.Empty) ||
               dueDate.Equals(String.Empty) ||
               owner.Equals(String.Empty))
            {
                Messenger.Show(Response, "Please fill all required fields!");
                return;
            }

            try
            {
                String strInsertDecision = "insert into mom_action (mom_id, action, status, duedate, owner) values " +
                    "(" + momID + ", '" + action + "', '" + status + "', '" + dueDate + "', '" + owner + "')";
                DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                localOperator.Update(strInsertDecision);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            // Clean up the fields
            txtAction.Text = String.Empty;
            txtActionSts.Text = String.Empty;
            txtActionDueDate.Text = String.Empty;
            ddlOwners.SelectedIndex = -1;

            RefreshGridViews(momID);
        }

        private void RefreshMOM(String momID)
        {
            // Clear the DataSourceID
            if (momID.Equals(String.Empty))
            {
                SqlDataSource1.SelectCommand = "select * from mom where 1 = 2";
            }
            else
            {
                SqlDataSource1.SelectCommand = "select * from mom where id = " + momID + " order by id";
            }

            SqlDataSource1.DataBind();

            //// Set DataSource
            //DataTable dt = MOMOperator.ReadMOMForGridView(momID);

            //grvMOM.DataSource = dt.DefaultView;
            //grvMOM.DataBind();

            //// Set DataSourceID
            //grvMOM.DataSource = null;
            //grvMOM.DataSourceID = "SqlDataSource1";
        }

        private void RefreshAgenda(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceAgenda.SelectCommand = "select * from mom_agenda where 1 = 2";
            }
            else
            {
                SqlDataSourceAgenda.SelectCommand = "select * from mom_agenda where mom_id = " + momID + " order by id";
            }
            SqlDataSourceAgenda.DataBind();
        }

        private void RefreshDecision(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceDecision.SelectCommand = "select * from mom_decision where 1 = 2";
            }
            else
            {
                SqlDataSourceDecision.SelectCommand = "select * from mom_decision where mom_id = " + momID + " order by id";
            }

            SqlDataSourceDecision.DataBind();
        }

        private void RefreshActions(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceActions.SelectCommand = "select * from mom_action where 1 = 2";
            }
            else
            {
                SqlDataSourceActions.SelectCommand = "select * from mom_action where mom_id = " + momID + " order by [owner], action";
            }

            SqlDataSourceActions.DataBind();
        }

        private void RefreshNotes(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceNotes.SelectCommand = "select * from mom_notes where 1 = 2";
            }
            else
            {
                SqlDataSourceNotes.SelectCommand = "select * from mom_notes where mom_id = " + momID + " order by id";
            }

            SqlDataSourceNotes.DataBind();
        }

        protected void btnActionReminder_Click(object sender, EventArgs e)
        {
            // If the selected node is not a MOM ID, then return
            TreeNode selectedNode = trvMOMs.SelectedNode;

            if (selectedNode == null // No node selected
                || selectedNode.Parent == null // root node selected
                || selectedNode.Parent.Parent == null // MOM type node selected
                )
            {
                Messenger.Show(Response, "Please Select a MOM then proceed.");
                return;
            }

            // If select the mom node
            String momID = selectedNode.Value;
            DataTable dt = MOMOperator.ReadActions(momID);

            MOMOperator.SendActionReminder(momID);

            Messenger.Show(Response, "Reminder Sent");
        }
    }
}
